<template>
  <div class="min-h-screen bg-pink-100 text-pink-800">
    <!-- Header -->
    <header class="border-b border-pink-200 p-4">
      <div class="container mx-auto flex justify-between items-center">
        <h1 class="text-2xl font-bold text-pink-600">数字键盘练习</h1>
        <div class="flex gap-4">
          <button class="hover:text-pink-500 transition-colors" @click="openDataDialog">
            <PlusCircleIcon class="h-6 w-6" />
          </button>
          <button class="hover:text-pink-500 transition-colors" @click="resetPractice">
            <RefreshCwIcon class="h-6 w-6" />
          </button>
          <button class="hover:text-pink-500 transition-colors" @click="showHelp = true">
            <HelpCircleIcon class="h-6 w-6" />
          </button>
        </div>
      </div>
    </header>

    <!-- Main Content -->
    <main class="container mx-auto px-4 py-8">
      <div class="max-w-2xl mx-auto">
        <!-- Practice Area -->
        <div class="bg-white rounded-3xl p-8 mb-6 shadow-xl box-border border-4 border-pink-300">
          <!-- Character Display -->
          <div class="mb-8 flex justify-center gap-2">
            <div 
              v-for="(char, index) in currentTarget" 
              :key="index"
              >
              <div 
                class="w-10 h-15 flex items-center justify-center rounded-md text-5xl font-mono font-medium relative"
                :class="{
                  'text-pink-600': index === userInput.length,
                  'text-gray-400': index >= userInput.length,
                  'text-green-400 bg-green-200/80': index < userInput.length && userInput[index] === char,
                  'text-red-400 bg-red-200/80': index < userInput.length && userInput[index] !== char
                }"
              >
                <span>{{ char }}</span>
                <div v-show="index === userInput.length" class="absolute left-0 bottom-0 w-full h-1 rounded-full bg-pink-400 animate-pulse"></div>
              </div>
            </div>
          </div>

          <!-- Virtual Numpad -->
          <div class="grid grid-cols-4 gap-2 max-w-[280px] mx-auto">
            <!-- Num Lock, /, *, - -->
            <button
              v-for="key in topRow"
              :key="key"
              @click="handleInput(key)"
              :class="[getButtonClass(key), { 'active-key': activeKeys.includes(key) }]"
            >
              {{ key }}
            </button>

            <!-- 7-8-9, + -->
            <button
              v-for="key in ['7', '8', '9']"
              :key="key"
              @click="handleInput(key)"
              :class="[getButtonClass(key), { 'active-key': activeKeys.includes(key) }]"
            >
              {{ key }}
            </button>
            <button
              class="bg-pink-200 hover:bg-pink-300 rounded-2xl p-4 text-xl font-bold transition-colors row-span-2 shadow-md"
              @click="handleInput('+')"
              :class="{ 'active-key': activeKeys.includes('+') }"
            >
              +
            </button>

            <!-- 4-5-6 -->
            <button
              v-for="key in ['4', '5', '6']"
              :key="key"
              @click="handleInput(key)"
              :class="[getButtonClass(key), { 'active-key': activeKeys.includes(key) }]"
            >
              {{ key }}
            </button>

            <!-- 1-2-3, Enter -->
            <button
              v-for="key in ['1', '2', '3']"
              :key="key"
              @click="handleInput(key)"
              :class="[getButtonClass(key), { 'active-key': activeKeys.includes(key) }]"
            >
              {{ key }}
            </button>
            <button
              class="bg-pink-300 hover:bg-pink-400 rounded-2xl p-2 text-sm font-bold transition-colors row-span-2 shadow-md"
              @click="handleInput('Enter')"
              :class="{ 'active-key': activeKeys.includes('Enter') }"
            >
              Enter
            </button>

            <!-- 0, . -->
            <button
              @click="handleInput('0')"
              class="bg-pink-200 hover:bg-pink-300 rounded-2xl p-4 text-xl font-bold transition-colors col-span-2 shadow-md"
              :class="{ 'active-key': activeKeys.includes('0') }"
            >
              0
            </button>
            <button
              @click="handleInput('.')"
              :class="[getButtonClass('.'), { 'active-key': activeKeys.includes('.') }]"
            >
              .
            </button>
          </div>
        </div>

        <!-- Stats -->
        <div class="flex justify-between items-center bg-white rounded-3xl p-4 box-border border-4 border-pink-300">
          <div>
            <span class="text-pink-600 font-medium">准确率:</span>
            <span class="ml-2 text-green-500 font-bold">{{ accuracy }}%</span>
          </div>
          <div>
            <span class="text-pink-600 font-medium">速度:</span>
            <span class="ml-2 font-bold">{{ speed }} 字/分钟</span>
          </div>
          <div>
            <span class="text-pink-600 font-medium">进度:</span>
            <span class="ml-2 font-bold">{{ progress }}%</span>
          </div>
        </div>
      </div>
    </main>

    <!-- Help Modal -->
    <div v-if="showHelp" class="fixed inset-0 bg-pink-100/90 bg-opacity-50 flex items-center justify-center">
      <div class="bg-white p-8 rounded-3xl max-w-md border-4 border-pink-300">
        <h2 class="text-2xl font-bold mb-4 text-pink-600">使用说明</h2>
        <ul class="list-disc list-inside space-y-2 mb-6 text-pink-800">
          <li>使用数字键盘输入显示的数字和运算符</li>
          <li>支持的运算符: + - * /</li>
          <li>按Enter确认并进入下一题</li>
          <li>保持准确性和速度的平衡</li>
          <li>宝宝😚♥♥</li>
        </ul>
        <button 
          @click="showHelp = false"
          class="bg-pink-400 hover:bg-pink-500 text-white px-6 py-2 rounded-full font-bold transition-colors"
        >
          关闭
        </button>
      </div>
    </div>

    <!-- Custom Exercise Modal -->
    <CustomExerciseModal
      v-if="showCustomExerciseModal"
      @close="cancelAddCustomExercises"
      @submit="addCustomExercises"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { RefreshCwIcon, HelpCircleIcon, PlusCircleIcon } from 'lucide-vue-next'
import CustomExerciseModal from './CustomExerciseModal.vue'

const topRow = ['Num', '/', '*', '-']

const exercises = reactive([
  '123+456',
])
const activeKeys = ref([])

const currentExerciseIndex = ref(0)
const userInput = ref('')
const startTime = ref(null)
const totalKeystrokes = ref(0)
const correctKeystrokes = ref(0)
const showHelp = ref(false)
const showCustomExerciseModal = ref(false)

const currentTarget = computed(() => exercises[currentExerciseIndex.value] || '')

const isCorrect = computed(() => {
  return userInput.value === currentTarget.value.slice(0, userInput.value.length)
})

const accuracy = computed(() => {
  if (totalKeystrokes.value === 0) return 100
  return Math.round((correctKeystrokes.value / totalKeystrokes.value) * 100)
})

const speed = computed(() => {
  if (!startTime.value) return 0
  const minutes = (Date.now() - startTime.value) / 60000
  return Math.round(totalKeystrokes.value / minutes)
})

const progress = computed(() => {
  return Math.round((currentExerciseIndex.value / exercises.length) * 100)
})

const openDataDialog = () => {
  showCustomExerciseModal.value = true
  // 移除键盘监听事件
  window.removeEventListener('keydown', handleKeydown, false)
}

const addCustomExercises = (newExercises) => {
  exercises.push(...newExercises)
  showCustomExerciseModal.value = false
  // 重置练习，从新添加的练习开始
  resetPractice()
  window.addEventListener('keydown', handleKeydown)
}

const cancelAddCustomExercises = () => {
  showCustomExerciseModal.value = false
  window.addEventListener('keydown', handleKeydown)
}

const getButtonClass = (key) => {
  return `bg-pink-200 rounded-2xl font-bold transition-colors shadow-md ${
    key === 'Num' ? 'text-pink-400 cursor-not-allowed p-2 text-sm' : ' hover:bg-pink-300 p-4 text-xl'
  }`
}

const handleInput = (key) => {
  if (!startTime.value && key !== 'Num') {
    startTime.value = Date.now()
  }

  if (key === 'Num') return

  // 添加按键动画
  activeKeys.value.push(key)
  setTimeout(() => {
    activeKeys.value = activeKeys.value.filter(k => k !== key)
  }, 100)

  if (key === 'Enter') {
    // if (userInput.value === currentTarget.value) {
      currentExerciseIndex.value = (currentExerciseIndex.value + 1) % exercises.length
      userInput.value = ''
    // }
    return
  }

  userInput.value += key
  totalKeystrokes.value++
  if (isCorrect.value) {
    correctKeystrokes.value++
  }

}

const resetPractice = () => {
  currentExerciseIndex.value = 0
  userInput.value = ''
  startTime.value = null
  totalKeystrokes.value = 0
  correctKeystrokes.value = 0
}

const handleKeydown = (e) => {
  const keyMap = {
    'Enter': 'Enter',
    'NumLock': 'Num',
    'Decimal': '.',
    '.': '.',
    '/': '/',
    '*': '*',
    '-': '-',
    '+': '+',
    '0': '0',
    '1': '1',
    '2': '2',
    '3': '3',
    '4': '4',
    '5': '5',
    '6': '6',
    '7': '7',
    '8': '8',
    '9': '9'
  }

  const key = keyMap[e.key]
  if (key) {
    e.preventDefault() // 防止默认行为
    handleInput(key)
  }
}
onMounted(() => {

  window.addEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
.active-key {
  animation: keyPress 0.1s ease-in-out;
}

@keyframes keyPress {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(0.9);
    background-color: theme('colors.pink.400');
  }
  100% {
    transform: scale(1);
  }
}

button {
  transition: all 0.2s ease;
}

.bg-pink-200, .bg-pink-300 {
  color: theme('colors.pink.900');
}
</style>